package com.googlecode.restitory.gae.http;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import com.google.appengine.api.urlfetch.HTTPResponse;
import com.googlecode.restitory.gae.GAERequestUtil;
import com.googlecode.restitory.gae.Request;
import com.googlecode.restitory.gae.Response;

public class FutureHttpReponse implements Future<Response> {

	private final Future<HTTPResponse> resp;
	private final Request request;

	public FutureHttpReponse(Request request, Future<HTTPResponse> resp) {
		this.request = request;
		this.resp = resp;
	}

	@Override
	public boolean cancel(boolean mayInterruptIfRunning) {
		return resp.cancel(mayInterruptIfRunning);
	}

	@Override
	public boolean isCancelled() {
		return resp.isCancelled();
	}

	@Override
	public boolean isDone() {
		return resp.isDone();
	}

	@Override
	public Response get() throws InterruptedException, ExecutionException {
		HTTPResponse response = resp.get();
		return GAERequestUtil.httpToResponse(response).setRequest(request);
	}

	@Override
	public Response get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
		HTTPResponse response = resp.get(timeout, unit);
		return GAERequestUtil.httpToResponse(response).setRequest(request);
	}

	@Override
	public String toString() {
		return "[FutureHttpResponse: " + request + "]";
	}

}
